<template>
	<div>

		<div class="content">

			<div class="header">
			<!-- 修改表单区域 -->
			<el-form :inline="!isMobile" :model="formInline" class="demo-form-inline">
			  <el-form-item label="查询条件" :style="isMobile ? 'width:100%' : ''">
			    <el-input v-model="formInline.user" placeholder="请输入平台名称" clearable />
			  </el-form-item>
			  <el-form-item :style="isMobile ? 'width:100%' : ''">
			    <el-button @click="fetchData(formInline.user)" style="width:100%">查询</el-button>
			  </el-form-item>
			</el-form>
			</div>
			<div class="area">
				<div class="tab-header">
					<div class="tabs">
						<el-button type="primary" @click="addOpen">添加</el-button>
					</div>
					<!-- <div class="tabs tabs-price">总余额：<span style="color: red;">0.0000</span>元</div> -->
					<div class="tabs tabs-price" >渠道额度：<span style="color: red;">{{nums || 0}} &nbsp; </span>个</div>
				</div>

				<div class="table-area">
					<el-table border :data="tableData" stripe style="width: 100%">
						<el-table-column prop="id" label="ID" />
						<el-table-column prop="name" label="对接名称" />
						<el-table-column prop="type_name" label="对接平台" />
						<el-table-column prop="url" label="对接域名" />
						<el-table-column prop="username" label="对接账号" />

				<el-table-column  label="渠道余额" #default="scope">
            <el-icon class="is-loading" v-if="!scope.row.num&&scope.row.num!==0">
              <Loading />
            </el-icon>
            <span class="shuaxin" @click="refreshBalance(scope.row)">  刷新</span>
            {{scope.row.num}}
						</el-table-column>

<el-table-column fixed="right" label="操作" min-width="120">
  <template #default="scope">
    <div :style="isMobile ? 'display: flex; flex-direction: column;' : ''">
      <el-button type="success" plain size="small" @click="btnDocking(scope.row.id)" style="margin-bottom:5px">
        一键对接
      </el-button>
      <el-button type="primary" plain size="small" @click="btnEdit(scope.row)" style="margin-bottom:5px">编辑</el-button>
      <el-button type="danger" plain size="small" @click="handleDelete(scope.row.id)">删除</el-button>
    </div>
  </template>
  </el-table-column>
					</el-table>
				</div>
        <!-- 新增分页组件 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
          />
        </div>
			</div>

		</div>


		<!-- 修改对话框宽度 -->
		<el-dialog
		  v-model="dialogVisible"
		  :title="titlename"
		  :width="isMobile ? '90%' : '60%'"
		  :before-close="handleClose"
		>
		   <div class="diolog-content">
			   <el-form :inline="true" :model="addform" class="demo-form-inline">
			       <el-form-item label="渠道名称">
			         <el-input v-model="addform.name" placeholder="请添写渠道名称" clearable />
			       </el-form-item>
			       <el-form-item label="渠道类型" style="width: 290px;">
			         <el-select
			           v-model="addform.type"
			           placeholder="请选择渠道类型"
			           clearable
					 @change="getchange"
			         >
			           <el-option v-for="item in dockingMenuList" :label="item.name" :value="item.id"    />
			         </el-select>
			       </el-form-item>
			     </el-form>
				 <div class="tabs-area">
				 	  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
				 	    <el-tab-pane label="基础配置" name="first">
				 			<!-- <div class="order-area">
								<div class="orders">
									<div class="orders-name">订单通知地址</div>
									<div class="orders-name" style="color: red;">https:demo.kasuhoue.digiianfidhihagddafdf</div>
									<div class="orders-name">商品通知地址</div>
									<div class="orders-name" style="color: red;">https:demo.kasuhoue.digiianfidhihagddafdf</div>
								</div>

							</div> -->
							<div style="margin-top: 18px;">
								<div>地址</div>
								<div style="margin-top: 6px;">
								
									
									<el-input 
										v-model="addform.url" 
										style="width: 353px;"
									   @input="handleUrlInput2(addform.url)"
										
										placeholder="输入域名/路径"
									/>

									<!-- <el-input v-model="addform.url" style="width: 440px" placeholder="对接域名，请带上http://,例如http://www.baidu.com">
									<template #prepend>Http://</template>
									</el-input> -->
									<div v-if="urlError2" class="error-text" style="color: red;">{{ urlError2 }}</div>
								</div>
								<div v-show="payuserid">
									<div style="margin-top: 12px;">{{payuserid}}</div>
								<div style="margin-top: 6px;">
									 <el-input v-model="addform.pay_userid" style="width: 353px" placeholder="请输入APPID" />
								</div>
								</div>
								<div v-show="paypassword">
									<div style="margin-top: 12px;">{{passwords}}</div>
								<div style="margin-top: 6px;">
									 <el-input v-model="addform.pay_password" style="width: 353px" placeholder="如不修改请保留为空" />
								</div>
								</div>
								<div v-show="usernametitle">
									<div style="margin-top: 12px;" v-show="nameShow">{{usernametitle}}</div>
								<div style="margin-top: 6px;" v-show="nameShow">
									 <el-input v-model="addform.username_title" style="width: 353px" placeholder="请输入账号" />
								</div>
								</div>
								<div v-show="paypassword">
									<div style="margin-top: 12px;"   v-show="nameShow" >{{ paypassword }}</div>
								    <div style="margin-top: 6px;" v-show="nameShow">
									 <el-input type="password" v-model="addform.password_title" style="width: 353px" placeholder="请输入密码" />
								</div>
								</div>
							</div>

							  <div class="dialog-footer">
							    <el-button @click="dialogVisible = false">取消</el-button>
							    <el-button type="primary" @click="submit()">
							      提交
							    </el-button>
							  </div>

				 		</el-tab-pane>
				 	    <!-- <el-tab-pane label="同步配置" name="second">
							<div class="configuration-area">
								<div class="configurations">
									<div>商品下架我方</div>
									<div>
										 <el-radio-group v-model="radio">
										    <el-radio :value="3">暂停</el-radio>
										    <el-radio :value="6">禁售</el-radio>

										  </el-radio-group>
									</div>
								</div>
								<div class="configurations">
									<div>商品同步</div>
									<div>
										 <el-checkbox
										     v-model="checkAll"
										     :indeterminate="isIndeterminate"
										     @change="handleCheckAllChange"
										   >
										     全选
										   </el-checkbox>
										   <el-checkbox-group
										     v-model="checkedCities"
										     @change="handleCheckedCitiesChange"
										   >
										     <el-checkbox v-for="city in cities" :key="city" :label="city" :value="city">
										       {{ city }}
										     </el-checkbox>
										   </el-checkbox-group>
									</div>
								</div>
								<div class="configurations">
									<div>同步订单配置</div>
									<div>
										 <el-checkbox
										     v-model="checkAll2"
										     :indeterminate="isIndeterminate2"
										     @change="handleCheckAllChange2"
										   >
										     全选
										   </el-checkbox>
										   <el-checkbox-group
										     v-model="checkedCities2"
										     @change="handleCheckedCitiesChange2"
										   >
										     <el-checkbox v-for="city in cities2" :key="city" :label="city" :value="city">
										       {{ city }}
										     </el-checkbox>
										   </el-checkbox-group>
									</div>
								</div>
							</div>
							<div class="dialog-footer">
							  <el-button @click="dialogVisible = false">取消</el-button>
							  <el-button type="primary" @click="dialogVisible = false">
							    提交
							  </el-button>
							</div>
						</el-tab-pane> -->

				 	  </el-tabs>
				 </div>

		   </div>

		  </el-dialog>
		  <docking   @update-node="handleUpdateNode" v-model="dockShow" :treeData="channelTreeData" :dockId="dockId" :isBd="1"></docking>
	</div>
</template>

<script lang="ts" setup>
	import {page,AddDock,dockingMenuPage,setdocking,balance,categoryDel,getDockingUserlnfo1} from '~/base/api/goods/channel.ts'
	import docking from './compent/index.vue'
	import { reactive,ref,onMounted ,onBeforeUnmount} from 'vue'
	import axios from 'axios';
  import { Loading } from '@element-plus/icons-vue'
  import {ElMessageBox, ElMessage, ElLoading} from 'element-plus'
import { error } from 'node:console';
	components: {
	  docking, Loading
	}
  const checkIsMobile = () => {
    isMobile.value = window.innerWidth <= 768
  }
  // 添加响应式检测
  const isMobile = ref(false)
   const isBd=ref(1)
	const nameShow=ref(false)
  const passwords=ref("")
  const paypassword=ref("")
  const payuserid=ref("")
  const usernametitle=ref("")
  const channelTreeData = ref([])   // 渠道树形结构数据
  const currentPage = ref(1) // 当前页码
  const pageSize = ref(10) // 每页显示数量
  const total = ref(0) // 总记录数
  const dockId = ref('')//
 const ids=ref("")
 const idss=ref("")
  const dockingMenuList=ref([])
	const tableData=ref([])
	const dockShow=ref(false)
    const defaults=ref(false)
	const dialogVisible=ref(false)
	const activeName = ref('first')
	const radio=ref(3)
	const titlename=ref('添加')
	const input=ref("")
	const input2=ref("")
	const input3=ref("")
    const nums=ref("")
	const formInline = reactive({
		user: '',
		region: '',
		date: '',
	})
  const addform = reactive({
    type: '',
    name: '',
    url: '',
    pay_userid: '',
    pay_password: '',
	username_title:"",
	password_title:"",
    username: '',
    password: '',
    otherConf: '',
	id:"",
  })
  function handleUpdateNode({ id, property, value }) {
// 更新树数据中对应节点的属性
  const updateNode = (nodes) => {
    return nodes.map(node => {
      if (node.id === id) {
        return { ...node, [property]: value };
      }
      if (node.list) {
        return { ...node, list: updateNode(node.list) };
      }
      return node;
    });
  };
  channelTreeData.value = updateNode(channelTreeData.value);
  }
  const queryBalance = async (row) => {

    try {
      const result = await getDockingUserlnfo1({ Docking: row.id });
      row.num = result.data.num;
      ElMessage.success('余额查询成功');
    } catch (error) {
      row.num = '查询失败';
      ElMessage.error('余额查询失败');
    } finally {

    }
  };
  // 添加refreshBalance方法
  const refreshBalance = async (row) => {
    try {
      const result = await getDockingUserlnfo1({ Docking: row.id })
      row.num = result.data.num
      ElMessage.success('刷新成功')
    } catch (error) {
      ElMessage.error('刷新失败')
    } finally {
    }
  }
  // 删除方法
  const handleDelete = (id: string) => {
    ElMessageBox.confirm('确定要删除这条记录吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      // 这里调用删除API
      categoryDel({id:id}).then(() => {
        ElMessage.success('删除成功');
        fetchData(); // 刷新列表
      });

    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
  };
	//商品同步
	const checkAll = ref(false)
	const isIndeterminate = ref(true)
	const checkedCities = ref([])
	const cities = ['库存数量', '商品价格', '商品状态', '商品名称']

	const handleCheckAllChange = (val: CheckboxValueType) => {
	  checkedCities.value = val ? cities : []
	  isIndeterminate.value = false
	}
	const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
	  const checkedCount = value.length
	  checkAll.value = checkedCount === cities.length
	  isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length
	}

	//订单配置同步
	const checkAll2 = ref(false)
	const isIndeterminate2 = ref(true)
	const checkedCities2 = ref([])
	const cities2 = ['同步订单', '同步退款', '下单错误', '处理返回']

	const handleCheckAllChange2 = (val: CheckboxValueType) => {
	  checkedCities2.value = val ? cities2 : []
	  isIndeterminate2.value = false
	}
	const handleCheckedCitiesChange2 = (value: CheckboxValueType[]) => {
	  const checkedCount2 = value.length
	  checkAll2.value = checkedCount2 === cities2.length
	  isIndeterminate2.value = checkedCount2 > 0 && checkedCount2 < cities2.length
	}
  const submit = () => {
	if(addform.url ==''){
		ElMessage.error('请输入路径')
		return
	}
	console.log(addform.url)
	if(!addform.name){
		ElMessage.error('请选择渠道名称')
		return
	}
	if(!addform.type){
		ElMessage.error('请选择渠道类型')
		return
	}

    AddDock(addform).then(() => {
      dialogVisible.value = false
      handleQuery() // 提交后刷新列表
    })
  }
  // 查询处理
  const handleQuery = () => {
    currentPage.value = 1 // 重置为第一页
    fetchData()
  }

  // 重置查询条件
  const handleReset = () => {
    formInline.user = ''
    handleQuery()
  }
  // 分页尺寸变化
  const handlePageSizeChange = (size: number) => {
    pageSize.value = size
    fetchData()
  }

  // 页码变化
  const handleCurrentPageChange = (page: number) => {
    currentPage.value = page
    fetchData()
  }
  // 统一数据获取函数
 const fetchData = async (name) => {
   try {
     // 1. 先获取基础数据
     const res = await page({
       page: currentPage.value,
       limit: pageSize.value,
       _key_word: name
     });

     if (res.code === 200) {
       // 2. 立即显示基础数据
       tableData.value = res.data.data || [];
       total.value = Number(res.data.count) || 0;

       // 3. 显示余额查询的loading
       // const loadingInstance = ElLoading.service({
       //   target: '.el-table', // 针对表格区域
       //   text: '正在查询渠道余额...',
       //   background: 'rgba(255, 255, 255, 0.7)'
       // });

       try {
         // 4. 并行查询每个渠道的余额
         await Promise.all(tableData.value.map(async (item) => {
           try {
             const ress = await getDockingUserlnfo1({ Docking: item.id });
             item.num = ress.data.num;
           } catch (error) {
             console.error(`获取渠道${item.id}余额失败:`, error);
             item.num = '';
           }
         }));

         // 5. 强制更新表格数据
         tableData.value = [...tableData.value];
       } finally {
         // 6. 无论成功失败都关闭loading
         loadingInstance.close();
       }
     }
   } catch (error) {
     console.error('获取数据失败:', error);
    //  ElMessage.error('数据加载失败');
   }
 };
 const protocol = ref('https://');
const path = ref('');

  //获取下拉
  function getchange(id){
    const selectedItem = dockingMenuList.value.find(item => item.id === id);
	if (selectedItem) {
		console.log('选中的名称2222:', selectedItem);
      // 现在你可以获取selectedItem的任意属性了，比如name
      nameShow.value = selectedItem.needShowUserAndPass;
	  passwords.value=selectedItem.password_title
	  paypassword.value=selectedItem.pay_password_title
	  payuserid.value=selectedItem.pay_userid_title
	  usernametitle.value=selectedItem.username_title
	  addform.url=selectedItem.defaultUrl
      // 或者你需要同时获取两个属性，比如id和name
      // 接下来你可以做你想做的事情，比如存到表单的其他字段里，或者触发其他方法
      // 例如：this.addform.typeName = name;
      console.log('选中的名称:', nameShow.value,selectedItem.needShowUserAndPass);
    }

}
	const onSubmit = () => {
		console.log('submit!')
	}
	const urlError2=ref("")
	function handleUrlInput2(val) {
  if (!val) {
    urlError2.value = "";
  } else if (!/^(https?:\/\/)/i.test(val)) {
    urlError2.value = "URL必须以 http:// 或 https:// 开头";
  } else {
    urlError2.value = "";
  }
}

	//打开弹框
	function addOpen(){
		clears()
    getDockingMenuPage()
		dialogVisible.value=true
		titlename.value='添加'

	}
	//清空
	function clears(){
		addform.type=''
		addform.name=''
		addform.url=''
		addform.pay_userid=''
		addform.pay_password=''
		addform.username_title=''
		addform.password_title=''
		addform.username=''
		addform.password=''
		addform.otherConf=''
		addform.id=''
	}
	//编辑打开
	function btnEdit(row){
	  console.log(row)
	  passwords.value=row.needRenderInputInfo.password_title
	  paypassword.value=row.needRenderInputInfo.pay_password_title
	  payuserid.value=row.needRenderInputInfo.pay_userid_title
	  usernametitle.value=row.needRenderInputInfo.username_title
	  nameShow.value=row.needRenderInputInfo.needShowUserAndPass
	
    addform.type= row.type
      addform.name=row.name
      addform.url=row.url
      addform.pay_userid=row.pay_userid
      addform.pay_password=row.pay_password
      addform.username=row.username
      addform.password=row.password
      addform.otherConf=row.otherConf
	  addform.username_title= row.username_title
	  addform.pay_password= row.pay_password
	  addform.username_title= row.needRenderInputInfo.username_title
	  addform.password_title= row.needRenderInputInfo.password_title
	  addform.id= row.id
	  addOpen.password_title=row.password_title
	  idss.value=row.id
    getDockingMenuPage()
		dialogVisible.value=true
		titlename.value='编辑'
	}
	//对接打开弹框
	function btnDocking(id){
    getSetdocking(id)
    dockId.value=id
		dockShow.value=true
	}


//获取余额
function getbalance(){
	let parm={
		Docking:ids.value
	}
	balance(89).then((res)=>{
		console.log('获取的这个数',res)
		nums.value=res.data.num
	})
}
//点击刷新
function btnqu(e){
	ids.value=e
	getbalance()
}

	onMounted(()=>{
     checkIsMobile()
      window.addEventListener('resize', checkIsMobile)
    fetchData() // 初始化加载数据
    getDockingMenuPage()
	})
  onBeforeUnmount(() => {
    window.removeEventListener('resize', checkIsMobile)
  })
  function getDockingMenuPage(){
    dockingMenuPage().then((res)=>{
      if(res.code == 200){
        dockingMenuList.value=res.data.dockList
      }
      console.log(dockingMenuList)
    })
  }
	//列表
	function getSetdocking(id){
    // 显示 loading
    const loadingInstance = ElLoading.service({
      target: '.el-dialog', // 针对对话框区域
      lock: true,
      text: '正在加载数据中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

//之前的
// if(res.code == 200){
// 			console.log('这个数据是什么',res.data.list_array)
// 			res.data.list_array.map(x=>{
// 			x.list.map(y=>{y.parentName=x.name})
// 			})
//         channelTreeData.value=res.data.list_array||[]
// 			}
// 		}).finally(() => {
//       // 数据加载完成后关闭 loading
//       loadingInstance.close();
//     });

    // setdocking({id:id}).then((res)=>{
		setdocking({ id: id }).then((res) => {
  console.log('接口返回数据:', res.data); // 先打印数据看结构是否正确
  if (res.code == 200) {
    const listArray = res.data.list_array || []; // 防止 null/undefined
    listArray.forEach((x) => {
      const list = x.list || []; // 防止 x.list 是 null
      list.forEach((y) => {
        y.parentName = x.name;
      });
    });
    channelTreeData.value = listArray;
  }else{
	console.log('走这里吗')
	channelTreeData.value=[]
  }
}).finally(() => {
  loadingInstance.close();
}).catch((error)=>{
	channelTreeData.value=[]
	ElMessage({
    showClose: true,
    message: error.msg,
    type: 'error',
  })
});

	}
</script>

<style scoped>

.pagination-container{
	display: flex;
    justify-content: center;
    margin-top: 24px
}
	.configurations{
		margin-top: 12px;
	}
	.configuration-area{

	}
	.dialog-footer{
		margin: 0 auto;
		margin-top: 30px;
		text-align: center;
	}
	.orders-name{
		margin-top: 12px;
	}
	.orders{
		margin-left: 12px;
	}
	.order-area{
		width: 98%;
		padding-bottom: 12px;
		border: 1px solid #409eff;
		background-color: #e8f4ff;
	}
	.tabs-area{
		margin-top: 12px
		;
	}
	.diolog-content{

	}
	.shuaxin{
		font-size: 12px;
		color: #409eff;
		padding-right: 2px;
		cursor: pointer;
	}
	.table-area {
		width: 98%;
		margin: 0 auto;
		margin-top: 30px;
	}

	.tabs-price {
		border: 1px solid #3333;
		padding: 5px 12px 3px 12px;

	}

	.tabs {
		margin-left: 10px;
	}

	.tab-header {
		display: flex;
		width: 100%;
	}

	.area {
		width: 100%;
		background-color: white;
		padding-bottom: 28px;
		margin-top: 18px;
		padding-top: 14px;
	}

	.content {
		width: 96%;
		margin: 0 auto;
		height: 80vh;
		margin-top: 26px;
	}

	.header {
		background-color: white;
		padding: 17px 0 1px 12px;
		border-radius: 8px
	}
.is-loading {
  animation: rotating 2s linear infinite;
}
@keyframes rotating {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
<style scoped>
/* 基础响应式设置 */
.content {
  width: 96%;
  margin: 0 auto;
  margin-top: 26px;
  padding-bottom: 20px;
}

/* 表格区域响应式 */
.table-area {
  width: 100%;
  margin: 0 auto;
  margin-top: 20px;
  overflow-x: auto;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  overflow-x: auto;
}

/* 对话框内容 */
.diolog-content {
  padding: 10px;
}

/* 标签页区域 */
.tabs-area {
  margin-top: 12px;
}

/* 配置区域 */
.configurations {
  margin-top: 12px;
}

/* 对话框底部按钮 */
.dialog-footer {
  margin: 20px auto 0;
  text-align: center;
}

/* 订单区域 */
.order-area {
  width: 100%;
  padding: 12px;
  border: 1px solid #409eff;
  background-color: #e8f4ff;
  box-sizing: border-box;
}

/* 刷新按钮样式 */
.shuaxin {
  font-size: 12px;
  color: #409eff;
  padding-right: 2px;
  cursor: pointer;
}

/* 加载动画 */
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (max-width: 768px) {
  /* 头部表单 */
  .header {
    padding: 10px;
  }

  /* 表单项目 */
  .el-form-item {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }

  /* 标签页 */
  .el-tabs {
    overflow-x: auto;
  }

  /* 对话框内容 */
  .diolog-content {
    padding: 5px;
  }

  /* 输入框宽度 */
  .el-input {
    width: 100% !important;
  }

  /* 表格操作按钮 */
  .el-table-column--fixed-right .el-button {
    margin-bottom: 5px;
  }

  /* 标签页头 */
  .tab-header {
    flex-direction: column;
  }

  .tabs {
    margin: 5px 0;
  }

  /* 对话框标题 */
  .el-dialog__title {
    font-size: 16px;
  }
}

/* PC端特定样式 */
@media (min-width: 769px) {
  .content {
    /* max-width: 1200px; */
  }

  .table-area {
    width: 98%;
  }

  .diolog-content {
    min-width: 500px;
  }

  .el-form--inline .el-form-item {
    margin-right: 10px;
  }
}
</style>
